import {
  SHOPCART_GET_DATA,
  SHOPCART_UPDATE_ITEM,
  SHOPCART_CHECKED_ALL,
  SHOPCART_CALCULATE_PRICE
} from '../mutation-types';
import request from '../../utils/wxRequest';

const state = {
  data: {},
  totalPrice: 0.00,
  selectCount: 0
};

const getters = {
  data: (state) => state.data,
  totalPrice: (state) => state.totalPrice,
  selectCount: (state) => state.selectCount
};

const mutations = {
  [SHOPCART_GET_DATA](state, payload) {
    state.data = payload.data;
  },
  [SHOPCART_UPDATE_ITEM](state, payload) {
    state.data[payload.idx] = payload.item;
    console.log(state.data);
  },
  [SHOPCART_CHECKED_ALL](state, payload) {
    console.log('check all start');
    const tempData = state.data;
    for (let i = 0, len = tempData.length; i < len; i++) {
      tempData[i].checked = payload.checked;
    }
    state.data = tempData;
    console.log('check all end');
  },
  [SHOPCART_CALCULATE_PRICE](state, payload) {
    console.log('开始计算价格');
    let totalPrice = 0.00;
    let selectCount = 0;
    const tempData = state.data;
    for (let i = 0, len = tempData.length; i < len; i++) {
      if (tempData[i].checked === true) {
        totalPrice += tempData[i].counter * tempData[i].price;
        selectCount += 1;
      }
    }

    state.totalPrice = totalPrice.toFixed(2);
    state.selectCount = selectCount;
  }
};

const actions = {
  [SHOPCART_GET_DATA]({ commit }) {
    // request.get('http://localhost:3000/cart')
    //   .then((res) => {
    //     commit({
    //       type: SHOPCART_GET_DATA,
    //       data: res.data
    //     });
    //     commit({
    //       type: SHOPCART_CALCULATE_PRICE
    //     });
    //   })
    //   .catch((e) => {
    //   });
  },
  [SHOPCART_UPDATE_ITEM]({ commit }, params) {
    console.log('准备更新');
    commit({
      type: SHOPCART_UPDATE_ITEM,
      item: params.item,
      idx: params.idx
    });
    commit({
      type: SHOPCART_CALCULATE_PRICE
    });
  },
  [SHOPCART_CHECKED_ALL]({ commit }, params) {
    console.log('全选商品action');
    commit({
      type: SHOPCART_CHECKED_ALL,
      checked: params.checked
    });
    commit({
      type: SHOPCART_CALCULATE_PRICE
    });
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};
